package rankSameScore

import (
	"fmt"
	"sort"
)

type ScoreRank struct {
	Rank  int32
	Id    int64
	Score int64
}

func (self *ScoreRank) String() string {
	return fmt.Sprintf("rank:%d, id:%d, score:%d", self.Rank, self.Id, self.Score)
}

type ScoreRanks []*ScoreRank

func (self ScoreRanks) Len() int {
	return len(self)
}
func (self ScoreRanks) Less(i, j int) bool {
	return self[i].Score > self[j].Score
}
func (self ScoreRanks) Swap(i, j int) {
	self[i], self[j] = self[j], self[i]
}

// if needSort false, scores should be from big to small
func RankSameScore(needSort bool, scores []*ScoreRank) {
	if needSort {
		sort.Sort(ScoreRanks(scores))
	}

	lastScore := int64(-1)
	lastRank := int32(-1)
	for i := int32(0); i < int32(len(scores)); i++ {
		score := scores[i].Score
		rank := i + 1
		if score != lastScore {
			lastScore = score
			lastRank = rank
		} else {
			rank = lastRank
		}
		scores[i].Rank = rank
	}
}
